package org.jetlinks.community.mstn.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.crud.events.EntityBeforeDeleteEvent;
import org.hswebframework.web.crud.events.EntitySavedEvent;
import org.jetlinks.community.auth.entity.OrganizationEntity;
import org.jetlinks.community.auth.enums.OrgType;
import org.jetlinks.community.auth.service.OrganizationService;
import org.jetlinks.community.mstn.entity.AliasCategoryEntity;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
@AllArgsConstructor
@Slf4j
public class OrganizationEntityEventHandler {

    private final DeviceAliasService deviceAliasService;

    /**
     * 更新机构时，同时更新数字孪生表的站点、分组名称
     *
     * @param event
     */
    @EventListener
    public void handleUpdate(EntitySavedEvent<OrganizationEntity> event) {
        event.async(
            Flux.fromIterable(event.getEntity())
                .flatMap(organizationEntity ->{
                        if (organizationEntity.getOrgType() == OrgType.site) {
                            return deviceAliasService.updateSiteName(organizationEntity.getId(), organizationEntity.getName());
                        } else if (organizationEntity.getOrgType() == OrgType.group) {
                            return deviceAliasService.updateGroupName(organizationEntity.getId(), organizationEntity.getName());
                        } else {
                            return Flux.empty();
                        }
                })
                .then()
        );
    }

    //禁止删除已有使用数字孪生的站点、分组
    @EventListener
    public void handleProtocolDelete(EntityBeforeDeleteEvent<OrganizationEntity> event) {
        event.async(
            Flux.fromIterable(event.getEntity())
                .flatMap(organizationEntity -> {
                    if (organizationEntity.getOrgType() == OrgType.site) {
                        return deviceAliasService.siteNotReferenced(organizationEntity.getId());
                    } else if (organizationEntity.getOrgType() == OrgType.group) {
                        return deviceAliasService.groupNotReferenced(organizationEntity.getId());
                    } else {
                        return Mono.empty();
                    }
                })
        );
    }

}
